package activities;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

import com.matchcalendar.R;

import dataFormat.CalendarTextData;

import algorithm.CalendarAlgorithm;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TimePicker;

public class SetScheduleActivity extends Activity {
	private SeekBar seekBarPriority;
	private Button buttonPrevious, buttonOverTime, buttonStartTime, buttonDone, buttonSunday,
	buttonMonday, buttonTuesday, buttonWednesday, buttonThursday, buttonFriday, buttonSaturday;
	private EditText editTextTitle, editTextPs;
	private Calendar startTimeCal = Calendar.getInstance();
	private Calendar overTimeCal = Calendar.getInstance();
	private Set<View> isTouched = new HashSet<View>();
	private Set<Integer> selectDaysSet = new HashSet<Integer>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_set_schedule);
		findView();
		setListenerOrAdapter();
		
		if (getIntent().getExtras().getInt("setType") == 0)
			addCalInitView();
		else
			modCalInitView();
	}

	private void findView() {
		seekBarPriority = (SeekBar) findViewById(R.id.seekBarPriority);
		buttonPrevious = (Button) findViewById(R.id.buttonPrevious);
		editTextTitle = (EditText) findViewById(R.id.editTextTitle);
		editTextPs = (EditText) findViewById(R.id.editTextPs);
		buttonStartTime = (Button) findViewById(R.id.buttonStartTime);
		buttonOverTime = (Button) findViewById(R.id.buttonOverTime);
		buttonSunday = (Button) findViewById(R.id.buttonSunday);
		buttonMonday = (Button) findViewById(R.id.buttonMonday);
		buttonTuesday = (Button) findViewById(R.id.buttonTuesday);
		buttonWednesday = (Button) findViewById(R.id.buttonWednesday);
		buttonThursday = (Button) findViewById(R.id.buttonThursday);
		buttonFriday = (Button) findViewById(R.id.buttonFriday);
		buttonSaturday = (Button) findViewById(R.id.buttonSaturday);
		buttonDone = (Button) findViewById(R.id.buttonDone);
	}
	
	private void setListenerOrAdapter() {
		buttonPrevious.setOnClickListener(new ButtonPreviousClick());
		seekBarPriority.setOnSeekBarChangeListener(new SeekBarPriorityChange());
		editTextTitle.setOnTouchListener(new EditTextsTouch());
		editTextTitle.setOnFocusChangeListener(new EditTextsFocusChange("標題"));
		editTextPs.setOnTouchListener(new EditTextsTouch());
		editTextPs.setOnFocusChangeListener(new EditTextsFocusChange("備註"));
		buttonStartTime.setOnClickListener(new ButtonStartTimeClick());
		buttonOverTime.setOnClickListener(new ButtonOverTimeClick());
		buttonSunday.setOnTouchListener(new ButtonDaysTouch());
		buttonMonday.setOnTouchListener(new ButtonDaysTouch());
		buttonTuesday.setOnTouchListener(new ButtonDaysTouch());
		buttonWednesday.setOnTouchListener(new ButtonDaysTouch());
		buttonThursday.setOnTouchListener(new ButtonDaysTouch());
		buttonFriday.setOnTouchListener(new ButtonDaysTouch());
		buttonSaturday.setOnTouchListener(new ButtonDaysTouch());
		buttonDone.setOnClickListener(new ButtonDoneClick());
	}
	
	private class ButtonPreviousClick implements Button.OnClickListener {

		@Override
		public void onClick(View v) {
			SetScheduleActivity.this.finish();
		}
	}
	
	private class SeekBarPriorityChange implements SeekBar.OnSeekBarChangeListener {

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
		}

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			if (seekBar.getProgress() <= 25)
				seekBar.setProgress(0);
			else if ((seekBar.getProgress() > 25 && seekBar.getProgress() <= 50) ||
					(seekBar.getProgress() > 50 && seekBar.getProgress() <= 75))
				seekBar.setProgress(50);
			else
				seekBar.setProgress(100);
		}
	}
	
	private class EditTextsTouch implements EditText.OnTouchListener {

		@Override
		public boolean onTouch(View view, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN && !isTouched.contains(view)) {
				((EditText) view).setText("");
				isTouched.add(view);
			}
			return false;
		}
	}
	
	private class EditTextsFocusChange implements EditText.OnFocusChangeListener {
		private String str;
		
		public EditTextsFocusChange(String str) {
			this.str = str;
		}

		@Override
		public void onFocusChange(View view, boolean hasFocus) {
			if (!hasFocus && ((EditText) view).getText().toString().equals("")) {
				((EditText) view).setText(str);
				isTouched.remove(view);
			}
		}
	}
	
	private class ButtonStartTimeClick implements Button.OnClickListener {
		private TimePicker startTimePicker;

		@Override
		public void onClick(View v) {
			startTimePicker = new TimePicker(SetScheduleActivity.this);
			startTimePicker.setIs24HourView(true);
			startTimePicker.setCurrentHour(startTimeCal.get(Calendar.HOUR_OF_DAY));
			startTimePicker.setCurrentMinute(startTimeCal.get(Calendar.MINUTE));
			startTimePicker.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);
			new AlertDialog.Builder(SetScheduleActivity.this)
			.setTitle("選擇開始時間")
			.setView(startTimePicker)
			.setNegativeButton("取消", null)
			.setPositiveButton("確定", new StartTimeDialogPositiveClick())
			.show();
		}
		
		private class StartTimeDialogPositiveClick implements DialogInterface.OnClickListener {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
				
				startTimeCal.set(Calendar.HOUR_OF_DAY, startTimePicker.getCurrentHour());
				startTimeCal.set(Calendar.MINUTE, startTimePicker.getCurrentMinute());
				buttonStartTime.setText(sdf.format(startTimeCal.getTime()));
			}
		}
	}
	
	private class ButtonOverTimeClick implements Button.OnClickListener {
		private TimePicker endTimePicker;

		@Override
		public void onClick(View v) {
			endTimePicker = new TimePicker(SetScheduleActivity.this);
			endTimePicker.setIs24HourView(true);
			endTimePicker.setCurrentHour(overTimeCal.get(Calendar.HOUR_OF_DAY));
			endTimePicker.setCurrentMinute(overTimeCal.get(Calendar.MINUTE));
			endTimePicker.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);
			new AlertDialog.Builder(SetScheduleActivity.this)
			.setTitle("選擇結束時間")
			.setView(endTimePicker)
			.setNegativeButton("取消", null)
			.setPositiveButton("確定", new OverTimeDialogPositiveClick())
			.show();
		}
		
		private class OverTimeDialogPositiveClick implements DialogInterface.OnClickListener {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
				
				overTimeCal.set(Calendar.HOUR_OF_DAY, endTimePicker.getCurrentHour());
				overTimeCal.set(Calendar.MINUTE, endTimePicker.getCurrentMinute());
				buttonOverTime.setText(sdf.format(overTimeCal.getTime()));
			}
		}
	}
	
	private class ButtonDaysTouch implements Button.OnTouchListener {

		@Override
		public boolean onTouch(View view, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				int day = 0;
				int id = view.getId();
				
				if (id == R.id.buttonSunday)
					day = 0;
				else if (id == R.id.buttonMonday)
					day = 1;
				else if (id == R.id.buttonTuesday)
					day = 2;
				else if (id == R.id.buttonWednesday)
					day = 3;
				else if (id == R.id.buttonThursday)
					day = 4;
				else if (id == R.id.buttonFriday)
					day = 5;
				else if (id == R.id.buttonSaturday)
					day = 6;
				if (selectDaysSet.contains(day)) {
					view.setBackgroundResource(R.color.gray3);
					selectDaysSet.remove(day);
				}
				else {
					view.setBackgroundResource(R.color.gray2);
					selectDaysSet.add(day);
				}
			}	
			return false;
		}
	}
	
	private class ButtonDoneClick implements Button.OnClickListener {

		@Override
		public void onClick(View arg0) {
			if (selectDaysSet.isEmpty()) {
				new AlertDialog.Builder(SetScheduleActivity.this)
				.setTitle("尚未選擇星期幾")
				.setMessage("請選擇星期幾")
				.setPositiveButton("好", null)
				.show();
			}
			else if (buttonOverTime.getText().toString().equals("結束時間")) {
				new AlertDialog.Builder(SetScheduleActivity.this)
				.setTitle("尚未設定結束時間")
				.setMessage("請設定結束時間")
				.setPositiveButton("好", null)
				.show();
			}
			else if (CalendarAlgorithm.compareTime(startTimeCal, overTimeCal) >= 0) {
				new AlertDialog.Builder(SetScheduleActivity.this)
				.setTitle("時間範圍錯誤")
				.setMessage("開始時間必須小於結束時間")
				.setPositiveButton("好", null)
				.show();
			}
			else if (!isTouched.contains(editTextTitle) || editTextTitle.getText().toString().equals("")) {
				new AlertDialog.Builder(SetScheduleActivity.this)
				.setTitle("尚未填寫標題")
				.setMessage("請填寫標題")
				.setPositiveButton("好", null)
				.show();
			}
			else {
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				Bundle startTimeBundle = new Bundle();
				Bundle overTimeBundle = new Bundle();
				ArrayList<Integer> dayList = new ArrayList<Integer>();
				
				for (int day: selectDaysSet)
					dayList.add(day);
				bundle.putIntegerArrayList("dayList", dayList);
				startTimeBundle.putInt("hour", startTimeCal.get(Calendar.HOUR_OF_DAY));
				startTimeBundle.putInt("minute", startTimeCal.get(Calendar.MINUTE));
				bundle.putBundle("startTime", startTimeBundle);
				overTimeBundle.putInt("hour", overTimeCal.get(Calendar.HOUR_OF_DAY));
				overTimeBundle.putInt("minute", overTimeCal.get(Calendar.MINUTE));
				bundle.putBundle("overTime", overTimeBundle);
				bundle.putString("title", editTextTitle.getText().toString());
				bundle.putString("ps", editTextPs.getText().toString());
				switch (seekBarPriority.getProgress()) {
					case 0:
						bundle.putInt("priority", 0);
						break;
					case 50:
						bundle.putInt("priority", 1);
						break;
					case 100:
						bundle.putInt("priority", 2);
				}
				if (getIntent().getExtras().getInt("setType") == 1)
					bundle.putInt("id", ((CalendarTextData)getIntent().getExtras().getParcelable("data")).getId());
				intent.putExtras(bundle);
				setResult(RESULT_OK, intent);
				SetScheduleActivity.this.finish();
			}
		}
	}
	
	private void addCalInitView() {
		Bundle bundle = getIntent().getExtras();
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
		
		selectDaysSet.add(bundle.getInt("day"));
		switch (bundle.getInt("day")) {
			case 0:
				buttonSunday.setBackgroundResource(R.color.gray2);
				break;
			case 1:
				buttonMonday.setBackgroundResource(R.color.gray2);
				break;
			case 2:
				buttonTuesday.setBackgroundResource(R.color.gray2);
				break;
			case 3:
				buttonWednesday.setBackgroundResource(R.color.gray2);
				break;
			case 4:
				buttonThursday.setBackgroundResource(R.color.gray2);
				break;
			case 5:
				buttonFriday.setBackgroundResource(R.color.gray2);
				break;
			case 6:
				buttonSaturday.setBackgroundResource(R.color.gray2);
		}
		startTimeCal.set(Calendar.HOUR_OF_DAY, bundle.getInt("time"));
		startTimeCal.set(Calendar.MINUTE, 0);
		buttonStartTime.setText(sdf.format(startTimeCal.getTime()));
	}
	
	private void modCalInitView() {
		CalendarTextData data = getIntent().getExtras().getParcelable("data");
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
		
		selectDaysSet.add(data.getDay());
		switch (data.getDay()) {
			case 0:
				buttonSunday.setBackgroundResource(R.color.gray2);
				break;
			case 1:
				buttonMonday.setBackgroundResource(R.color.gray2);
				break;
			case 2:
				buttonTuesday.setBackgroundResource(R.color.gray2);
				break;
			case 3:
				buttonWednesday.setBackgroundResource(R.color.gray2);
				break;
			case 4:
				buttonThursday.setBackgroundResource(R.color.gray2);
				break;
			case 5:
				buttonFriday.setBackgroundResource(R.color.gray2);
				break;
			case 6:
				buttonSaturday.setBackgroundResource(R.color.gray2);
		}
		startTimeCal.set(Calendar.HOUR_OF_DAY, data.getStartHour());
		startTimeCal.set(Calendar.MINUTE, data.getStartMinute());
		buttonStartTime.setText(sdf.format(startTimeCal.getTime()));
		overTimeCal.set(Calendar.HOUR_OF_DAY, data.getOverHour());
		overTimeCal.set(Calendar.MINUTE,data.getOverMinute());
		buttonOverTime.setText(sdf.format(overTimeCal.getTime()));
		editTextTitle.setText(data.getTitle());
		isTouched.add(editTextTitle);
		editTextPs.setText(data.getPs());
		switch (data.getPriority()) {
			case 0:
				seekBarPriority.setProgress(0);
				break;
			case 1:
				seekBarPriority.setProgress(50);
				break;
			case 2:
				seekBarPriority.setProgress(100);
		}
	}
}
